#include "Setupthread.h"
#include <QApplication>
#include <QDebug>
#include <QRegularExpression>
#include <QProcess>


void SetupThread::run()
{
    QString QStrDir = QString("cd %1 && SetupTool.exe ").arg(QCoreApplication::applicationDirPath());
    QStrDir.append(CmdPar);
    QString Result;

    if (CmdPar.contains("export"))
    {
        Result = "导出";
    }
    else
    {
        Result = "导入";
    }

    static QProcess SetupPro;
    connect = QObject::connect(&SetupPro, &QProcess::readyReadStandardOutput, this, [&](){
        QRegularExpression regex(R"(\[(\d{3})%\])");
        QRegularExpressionMatch match = regex.match(SetupPro.readAllStandardOutput());
        if (match.hasMatch())
        {
             int number = match.captured(1).toInt();
             QMetaObject::invokeMethod(this, "ProcessNotify", Qt::QueuedConnection, Q_ARG(int, number));
             if (number == 100)
             {
                 disconnect(connect);
             }
        }
        });

    SetupPro.start("cmd.exe", QStringList() << "/C" << QStrDir);

    SetupPro.waitForFinished(-1); // 等待进程完成

    int exitCode = SetupPro.exitCode();

    if (exitCode) {
        // 发生错误
        Result.append("失败");
    } else {
        // 输出运行结果
        Result.append("成功");
    }


    emit ResultNotify(Result);

}

bool SetupThread::GetPlatInfo(void)
{
    QProcess process;
    QString Cmd = QCoreApplication::applicationDirPath();
    Cmd.append("/SetupTool.exe -h");
    process.start(Cmd);
    process.waitForFinished(-1);
    QByteArray result = process.readAllStandardOutput();
    QString resultString = QString::fromLocal8Bit(result);

    if (resultString.contains("plat is NULL"))
    {
        return false;
    }
    else
    {
        return true;
    }
}


void SetupThread::SetCmdPar(QString Par)
{
    CmdPar = Par;
}
